<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px" class="search-form">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="classId">
        <el-tree-select
          v-model="selectedClassId"
          :data="classTreeData"
          :props="treeProps"
          placeholder="请选择商品分类"
          clearable
          check-strictly
          :render-after-expand="false"
          @change="handleClassChange"
        />
      </el-form-item>
      <el-form-item label="商品状态" prop="goodsStatus">
        <el-select v-model="queryParams.goodsStatus" placeholder="请选择商品状态" clearable>
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['lkshop:good:add']"
        >新增商品</el-button>
      </el-col>
    

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="goodsId" width="80" />
      <el-table-column label="商品名称" align="center" prop="goodsName" min-width="150" />
      <el-table-column label="商品分类" align="center" prop="classId" width="120" />
      <el-table-column label="商品价格" align="center" prop="goodsPrice" width="100">
        <template #default="scope">
          ¥{{ scope.row.goodsPrice }}
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="center" prop="goodsNumber" width="100" />
      <el-table-column label="商品状态" align="center" prop="goodsStatus" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.goodsStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="上架"
            inactive-text="下架"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品图片" align="center" prop="goodsImg" width="100">
        <template #default="scope">
          <ImagePreview :src="scope.row.goodsImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['lkshop:good:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lkshop:good:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="Goods">
import * as goodsApi from "@/api/lkshop/goods";
import * as goodClassApi from "@/api/lkshop/good_class";
import * as businessClassApi from "@/api/lkshop/businessClass";
import useUserStore from "@/store/modules/user";
import ImagePreview from "@/components/ImagePreview/index.vue";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const goodList = ref([]);
const classOptions = ref([]);
const classTreeData = ref([]);
const selectedClassId = ref(null);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessId: null,
    goodsName: null,
    classId: null,
    goodsStatus: null
  }
});

const { queryParams } = toRefs(data);

/** 查询商品管理列表 */
function getList() {
  loading.value = true;
  // 使用用户存储中的商家ID
  const businessId = userStore.businessId;
  console.log('=== 商品列表页面获取商家ID ===');
  console.log('用户存储:', userStore);
  console.log('用户存储中的商家ID:', businessId);
  
  if (!businessId) {
    console.warn('未找到商家ID，无法获取商品列表');
    proxy.$modal.msgWarning("未找到商家信息，请重新登录");
    loading.value = false;
    return;
  }
  
  queryParams.value.businessId = businessId;
  console.log('开始获取商品列表，商家ID:', businessId);
  goodsApi.listGood(queryParams.value).then(response => {
    console.log('商品列表获取成功:', response);
    goodList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch((error) => {
    console.error('获取商品列表失败:', error);
    loading.value = false;
  });
}

/** 查询商品分类列表 */
function getClassList() {
  goodsApi.listGood_class({}).then(response => {
    console.log('商品分类列表数据:', response.rows);
    classOptions.value = response.rows;
  }).catch((error) => {
    console.error('获取商品分类列表失败:', error);
    // 分类加载失败，不影响主要功能
  });
}

/** 查询商品分类树形结构 */
function getClassTreeData() {
  goodClassApi.getGood_classTree({}).then(response => {
    console.log('商品分类树形数据:', response.data);
    classTreeData.value = response.data || [];
  }).catch((error) => {
    console.error('获取商品分类树形数据失败:', error);
    classTreeData.value = [];
  });
}

/** 查询店铺分类树形结构 */
function getBusinessClassTreeData() {
  const businessId = userStore.businessId;
  console.log('=== 商品列表页面获取店铺分类 ===');
  console.log('商家ID:', businessId);
  
  if (!businessId) {
    console.warn('未找到商家ID，无法获取店铺分类');
    return;
  }
  
  businessClassApi.getBusinessClassTree({ businessId: businessId }).then(response => {
    console.log('店铺分类树形数据:', response.data);
    // 这里可以设置店铺分类数据，如果需要的话
  }).catch((error) => {
    console.error('获取店铺分类失败:', error);
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  selectedClassId.value = null;
  queryParams.value.classId = null;
  handleQuery();
}

/** 商品分类选择变化 */
function handleClassChange(value) {
  if (value) {
    // 如果选择了分类，将选择的分类ID设置到查询参数中
    queryParams.value.classId = value;
  } else {
    queryParams.value.classId = null;
  }
  console.log('选择的分类ID:', value);
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.goodsId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push('/lkshop/goods/add');
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const goodsId = row.goodsId || ids.value;
  proxy.$router.push(`/lkshop/goods/edit/${goodsId}`);
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodRef"].validate(valid => {
    if (valid) {
      if (form.value.goodsId != null) {
        goodsApi.updateGood(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        goodsApi.addGood(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const goodsIds = row.goodsId || ids.value;
  proxy.$modal.confirm('是否确认删除商品编号为"' + goodsIds + '"的数据项？').then(function() {
    return goodsApi.delGood(goodsIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 处理商品状态变更 */
function handleStatusChange(row) {
  const text = row.goodsStatus === 1 ? '上架' : '下架';
  goodsApi.updateGood(row).then(() => {
    proxy.$modal.msgSuccess(`商品${text}成功`);
  }).catch(() => {
    // 如果更新失败，回滚状态
    row.goodsStatus = row.goodsStatus === 1 ? 0 : 1;
  });
}

getList();
getClassList();
getClassTreeData();
getBusinessClassTreeData();
</script>

<style scoped>
/* 搜索表单样式 */
.search-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 15px;
  margin-right: 20px;
}

.search-form :deep(.el-input) {
  width: 200px;
}

.search-form :deep(.el-select) {
  width: 200px;
}

.search-form :deep(.el-tree-select) {
  width: 200px;
}

/* 表头样式 */
:deep(.el-table th) {
  background: #409eff !important;
  color: #ffffff !important;
  font-weight: 600;
  font-size: 14px;
  text-align: center;
}

:deep(.el-table th .cell) {
  color: #ffffff !important;
}

/* 表格整体样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

:deep(.el-table tbody tr:hover) {
  background: #f8f9fa;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
}

/* 开关样式 */
:deep(.el-switch) {
  margin: 0 5px;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
  font-size: 12px;
}

/* 分页样式 */
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  font-size: 14px;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #409eff;
  color: #ffffff;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: #409eff;
  color: #ffffff;
}
/* 美化树形选择器 */
:deep(.el-tree-select) {
  width: 100%;
}

:deep(.el-tree-select .el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  background: #ffffff;
}

:deep(.el-tree-select .el-input__wrapper.is-focus) {
  border-color: #409eff;
}

/* 美化下拉树形组件 */
:deep(.el-tree-select__popper) {
  border-radius: 6px;
  border: 1px solid #e9ecef;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-tree-select__popper .el-tree) {
  background: #ffffff;
  border-radius: 6px;
  padding: 12px;
}

:deep(.el-tree-select__popper .el-tree-node__content) {
  height: 40px;
  border-radius: 4px;
  margin: 2px 0;
  font-size: 14px;
}

:deep(.el-tree-select__popper .el-tree-node__content:hover) {
  background: #f8f9fa;
  color: #333333;
}

:deep(.el-tree-select__popper .el-tree-node__label) {
  font-weight: 500;
}

/* 美化表格 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

:deep(.el-table th) {
  background: #409eff;
  color: #ffffff;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

:deep(.el-table tbody tr:hover) {
  background: #f8f9fa;
}

/* 美化按钮 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
}

/* 美化标签 */
:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
  font-size: 12px;
}

/* 美化分页 */
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  font-size: 14px;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #409eff;
  color: #ffffff;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: #409eff;
  color: #ffffff;
}
</style>
